package own.stu.jobgib.playown.netty.im.client.common;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCounted;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;
import java.util.concurrent.ThreadPoolExecutor;

import static own.stu.jobgib.playown.netty.im.server.Server.CONNECT_ID;
import static own.stu.jobgib.playown.netty.im.server.Server.connectIdAttr;

@ChannelHandler.Sharable
public class ConsoleHandler extends ChannelInboundHandlerAdapter {
    protected final Logger logger = LoggerFactory.getLogger(getClass().getName());

    ThreadPoolExecutor executor;
    Scanner scanner;

    public ConsoleHandler(ThreadPoolExecutor executor) {
        this.executor = executor;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        scanner = new Scanner(System.in);
        System.out.println("channelActive");
        executor.submit(() -> {
            String line = "";
            while ((line = scanner.nextLine()) != null) {
                System.out.println("client send msg: " + line);
                if ("quit".equals(line)) {
                    break; // 怎么优雅关掉客户端
                }
                ctx.channel().writeAndFlush(line);
            }
            ctx.channel().close();
            // System.out.println(" ------ do run ");
        });
        ctx.fireChannelActive();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        Attribute<Long> attr = ctx.channel().attr(connectIdAttr);
        Long connectId = attr.get();
        logger.info("connect_id: {}", connectId);
        super.channelRegistered(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("get response from server: " + msg);
        if (msg instanceof ReferenceCounted) {
            ((ReferenceCounted) msg).release();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(" ConsoleHandler . channelInactive");
        scanner.close();
        super.channelInactive(ctx);
    }
}